var _VIEW_PATH = '../app_module/diy/views/';

var AV = require('leanengine');
var async = require('async');

var M = require('../models');

var orderM = M.orderM;
var addrM = M.addrM;
var cartM = M.cartM;

module.exports = {

    /**
     * 跳转到确认订单页面
     * Created by James at 2016-01-30
     * @param req
     * @param res
     * @param next
     */
    confirm:function(req,res,next){
        var userid = req.AV.user.id;              // 用户编号
        console.log(userid);
        var openid = req.AV.user.get('openid');   // 用户openid
        var total = 0;                            // 订单总金额
        var goods = [];                           // 订单商品

        //用户地址为空，代表是从购物车模块跳转过来的
        addrM.list().then(function(obj){
            if(obj.length == 0){
                //没有地址，则跳转到新增地址页面
                var url = '/order/confirm/';
                res.redirect('/user/center/address?back='+url);
            }else{
                async.waterfall([
                    //通过userid获取用户订单的商品
                    function(callback){
                        cartM.getProductList(userid,true).then(function(result){
                            var psid;
                            var cid;
                            var specArray;
                            var imgArray;
                            if (result.rows > 0) {
                                for (x in result.data) {
                                    psid = result.data[x].get('psid'); //读取购物车单条数据的商品规格ID
                                    cid = result.data[x].get('product').get('cid');
                                    specArray = result.data[x].get('product').get('spec'); //读取商品规格数组
                                    imgArray = JSON.parse(result.data[x].get('product').get('picurlarray'));//读取商品图片数组
                                    goods.push(
                                        {
                                            pid:        result.data[x].get('pid'),
                                            pname:      result.data[x].get('product').get('name'),
                                            sid:        result.data[x].get('psid'),
                                            cid:        cid,
                                            sname:      specArray[psid]['name'],
                                            price:      parseInt(specArray[psid]['grprice']),
                                            size:       parseInt(result.data[x].get('number')),
                                            img:        imgArray[0],
                                            point:      specArray[psid]['point'],
                                            pointRate:  specArray[psid]['pointRate'],
                                            isPoint:    specArray[psid]['isPoint'],
                                            isDiscount: specArray[psid]['isDiscount']
                                        }
                                    )


                                }
                            }
                            callback(null);
                        });
                    },
                    //获取购物车商品总价
                    function(callback){
                        cartM.getGoodsPrice(userid).then(function (result) {
                            total = result.GoodsPrice;
                            callback(null,{cartList:goods,total:total});
                        }).catch(function(err){
                            callback({code:9999,reason:err});   //code:9999 系统错误
                        });
                    }
                ],function(err,result){
                    if(err){
                        res.error(err);
                    }
                    if(result.cartList.length == 0){
                        //如果没有商品，则跳转到首页
                        res.redirect('/');
                    }else{
                        res.render(_VIEW_PATH + 'order/confirm',{title:'确认订单',cart:result.cartList,total:result.total});
                    }
                });
            }
        }).catch(function(err){
            res.error(err);
        });

    },
    /**
     * 生成订单
     * Created by James at 2016-01-30
     * @param req
     * @param res
     * @param next
     */
    addOrder:function(req,res,next){
        var data = req.query;//获取表单参数

        var total = parseFloat(data.total);
        var payway = data.payway;
        var str = '门店付款';
        var status = 8000;

        if(payway =='wx_pay'){
            str = '微信支付';
            status = 1000;
        }

        var uid = req.AV.user.id;
        var goods = new Array();
        var timestamp = new Date().getTime();
        var orderid = 'D'+timestamp;

        async.waterfall([
            //通过uid获取用户订单的商品
            function(callback){
                cartM.getProductList(uid,true).then(function(result){
                    var pid;
                    var psid;
                    var specArray;
                    var cid;
                    var imgArray;
                    var pro_num = 0;

                    if (result.rows > 0) {
                        for (x in result.data) {
                            pid = result.data[x].get('pid'); //读取购物车单条数据的商品ID
                            psid = result.data[x].get('psid'); //读取购物车单条数据的商品规格ID
                            pro_num = result.data[x].get('number');

                            if(parseInt(pro_num) <= 0){
                                return callback({code:506});   //code:506 购买商品数量为0
                            }

                            specArray = result.data[x].get('product').get('spec'); //读取商品规格数组
                            cid = result.data[x].get('product').get('cid'); //读取商品的分类编号
                            imgArray = JSON.parse(result.data[x].get('product').get('picurlarray'));//读取商品图片数组
                            goods.push(
                                {
                                    pid:        pid,
                                    pname:      result.data[x].get('product').get('name'),
                                    sid:        psid,
                                    cid:        cid,
                                    sname:      specArray[psid]['name'],
                                    price:      parseInt(specArray[psid]['grprice']),
                                    size:       parseInt(result.data[x].get('number')),
                                    img:        imgArray[0],
                                    point:      specArray[psid]['point'],
                                    pointRate:  specArray[psid]['pointRate'],
                                    isPoint:    specArray[psid]['isPoint'],
                                    isDiscount: specArray[psid]['isDiscount']
                                }
                            );
                        }
                        callback(null);
                    }else{
                        callback({code:505});   //code:505 购物车内已无商品，请刷新页面
                    }
                });
            },
            //生成订单
            function(callback){
                data['goods']=goods;
                data['total']=parseFloat(parseFloat(total).toFixed(2));
                data['description']=str+':'+parseFloat(total).toFixed(2)+' 元';
                var jsontext = '[{"way":"'+str+'","pay":'+parseFloat(total).toFixed(2)+'}]';
                data['orderid'] = orderid;
                data['oid'] = orderid;
                data['payway']=str;
                data['uid']=uid;
                data['status']=status;
                data['canceltime']=timestamp+(2*60*60);
                data['details']=JSON.parse(jsontext);

                if(str=="微信支付"){
                    data['syncStatus']=0;
                }else {
                    data['syncStatus']=1;
                    data['paytime']=timestamp;
                }

                orderM.addOrderPro(data).then(function(result){
                    //保存成功
                    callback(null);
                }).catch(function(err){
                    //保存失败
                    callback({code:9999,reason:err});   //code:9999 系统错误
                });
            },
            //删除购物车商品
            function(callback){
                cartM.delCartPro(uid).then(function(result){
                    callback(null,{code:0,orderid:orderid,fee:total*100});
                }).catch(function(err){
                    callback({code:9999,reason:err});   //code:9999 系统错误
                });
            }
        ],function(err,result){
            if(err){
                res.json(err);
            }
            res.json(result);
        });
    },
    /**
     * 生成订单(新增送三种果汁)
     * Created by James at 2016-01-30
     * @param req
     * @param res
     * @param next
     */
    diyaddOrder:function(uid,pid){

        if(!uid){
            return new AV.Promise.error({code:1001});        //用户编号不能为空
        }

        if(!pid){
            return new AV.Promise.error({code:1002});        //商品编号不能为空
        }

        var promise = new AV.Promise();

        var total = 0;
        var pname = '';
        var img = '';

        var data = {};

        if(pid == 881){
            total = 0;
            pname = '（元宵活动）特级阿克苏冰糖心苹果';
            img = 'http://7xj380.com1.z0.glb.clouddn.com/2016-02-15_56c18fc3302fd.jpg';
        }else if(pid == 588){
            total = 0;
            pname = '（元宵活动）阿克苏苹果汁';
            img = 'http://7xj380.com1.z0.glb.clouddn.com/2015-11-19_564d45e8b04b1.jpg';
        }

        var str = '门店付款';
        var goods = new Array();
        goods.push(
            {
                pid:        pid,
                pname:      pname,
                sid:        0,
                cid:        0,
                sname:      "1份",
                price:      total,
                size:       1,
                img:        img,
                point:      "0",
                pointRate:  "0",
                isPoint:    "0",
                isDiscount: "0"
            }
        );
        var timestamp = new Date().getTime();
        var orderid = 'D'+timestamp;
        async.waterfall([
            //生成订单
            function(callback){
                data['goods']=goods;
                data['total']=total;
                data['description']=str+':'+total+' 元';
                var jsontext = '[{"way":"'+str+'","pay":'+total+'}]';
                data['orderid'] = orderid;
                data['oid'] = orderid;
                data['payway']=str;
                data['uid']=uid;
                data['status']=8000;
                data['canceltime']=timestamp+(2*60*60);
                data['details']=JSON.parse(jsontext);
                data['storeName']='全站通用';
                data['syncStatus']=1;
                data['paytime']=timestamp;
                orderM.addOrderPro(data).then(function(result){
                    //保存成功
                    callback(null,{code:0,orderid:orderid,fee:total*100});
                }).catch(function(err){
                    //保存失败
                    callback({code:9999,reason:err});   //code:9999 系统错误
                });
            }
        ],function(err,result){
            if(err){
                promise.reject(err);
            }
            promise.resolve(result);
        });

        return promise;
    },
    /**
     * 跳转到确认订单页面
     * Created by James at 2016-01-30
     * @param req
     * @param res
     * @param next
     */
    chongzhi:function(req,res,next){
        res.render('user/chongzhi',{title:'用户充值'});
    }
}